package com.mercury.security.config;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;

import javax.annotation.Resource;


/**
 * 1. 支持remoteTokenServices 负载均衡
 * 2. 支持 获取用户全部信息
 * 3. 接口对外暴露，不校验 Authentication Header 头
 *
 * @author mercury
 */
@Slf4j
@RequiredArgsConstructor
public class AuthResourceServerConfigurerAdapter extends ResourceServerConfigurerAdapter {

    private final AuthResourceExceptionEntryPoint authResourceExceptionEntryPoint;

    private final PermitAllUrlProperties permitAllUrl;

    private final AuthBearerTokenExtractor authBearerTokenExtractor;

    private final ResourceServerTokenServices resourceServerTokenServices;

    /**
     * 默认的配置，对外暴露
     *
     * @param httpSecurity httpSecurity
     */
    @Override
    @SneakyThrows
    public void configure(HttpSecurity httpSecurity) {
        // 允许使用iframe 嵌套，避免swagger-ui 不被加载的问题
        httpSecurity.headers().frameOptions().disable();
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity
                .authorizeRequests();
        permitAllUrl.getUrls().forEach(url -> registry.antMatchers(url).permitAll());
        registry.anyRequest().authenticated().and().csrf().disable();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.authenticationEntryPoint(authResourceExceptionEntryPoint)
                .tokenExtractor(authBearerTokenExtractor)
                .tokenServices(resourceServerTokenServices);
    }

}
